package com.cfun.mylearn.Support.utils;

import android.content.Context;
import android.content.SharedPreferences;

import com.zhejiangdaily.ZhejiangDailyApplication;
import com.zhejiangdaily.constant.Constants;
import com.zhejiangdaily.constant.Spkeys;

public abstract class ResourceWrite {

	private static final String SP_NAME = Constants.SP_NAME;
	
	public static final void remove(String spKey) {
		SharedPreferences sp = ZhejiangDailyApplication.getInstance().getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
		SharedPreferences.Editor editor = sp.edit();
		editor.remove(spKey);
		editor.commit();
	}

	public static final void write2sp(String spKey, Object spValue) {
		write2sp(ZhejiangDailyApplication.getInstance(), SP_NAME, spKey, spValue);
	}

	/**
	 * 把数据写入SharedPreferences SharedPreferences很sb的不支持double型 所以如果传进去的数据是double型
	 * 拿出来的时候要注意是fload型的
	 * 
	 * @param context
	 * @param spName
	 * @param spKey
	 * @param spValue
	 */
	public static final void write2sp(Context context, String spName, String spKey, Object spValue) {
		SharedPreferences sp = context.getSharedPreferences(spName, Context.MODE_PRIVATE);
		SharedPreferences.Editor editor = sp.edit();
		if (spValue instanceof Integer) {
			int i = ((Integer) spValue).intValue();
			editor.putInt(spKey, i);
		} else if (spValue instanceof String) {
			String s = String.valueOf(spValue);
			editor.putString(spKey, s);
		} else if (spValue instanceof Double) {
			float d = Float.parseFloat(String.valueOf(spValue));
			editor.putFloat(spKey, d);
		} else if (spValue instanceof Float) {
			float f = ((Float) spValue).floatValue();
			editor.putFloat(spKey, f);
		} else if (spValue instanceof Boolean) {
			boolean b = ((Boolean) spValue).booleanValue();
			editor.putBoolean(spKey, b);
		} else if (spValue instanceof Long) {
			long l = ((Long) spValue).longValue();
			editor.putLong(spKey, l);
		} else {
			editor.remove(spKey);
		}
		editor.commit();
	}
	
	public static final void clear(){
		SharedPreferences sp = ZhejiangDailyApplication.getInstance().getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
		SharedPreferences.Editor editor = sp.edit();
		String server_host = sp.getString(Spkeys.SP_SERVER_HOST, "");
		String city_host = sp.getString(Spkeys.SP_DEVELOP_LOCATE_CITY, "");
		editor.clear();
		editor.commit();
		//清空数据 但保留host设置
		write2sp(Spkeys.SP_SERVER_HOST, server_host);
		write2sp(Spkeys.SP_DEVELOP_LOCATE_CITY, city_host);
	}
}
